package com.imooc.security.browser.controller;

import com.imooc.core.entity.SecurityProperties;
import com.imooc.security.browser.entity.SimpleResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录时，跳转到这里
 *
 * @author Created By Houce
 * @date 2020-07-28 14:53
 */
@RestController
@Slf4j
public class LoginRouteController {

    private RequestCache requestCache = new HttpSessionRequestCache();

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Resource
    private SecurityProperties securityProperties;

    /**
     * 动态跳转到登录页面
     *
     * @param request 登录请求
     * @param response 响应
     * @return 跳转结果
     * @throws IOException 异常
     */
    @GetMapping("/authentication/require")
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //获取到当前登录请求
        final SavedRequest savedRequest = requestCache.getRequest(request, response);
        if (null != savedRequest){
            String url  = savedRequest.getRedirectUrl();
            log.info("引发重定向跳转的目标URL地址是：{}",url);
            if (StringUtils.endsWith(url,".html")){
                //如果是浏览器访问，重定向到登录页上去，登录页认证成功后，会在successHandler中重定向到一开始request请求的目标页面
                log.info("开始重定向页面，准备跳转到：{}",securityProperties.getBrowser().getLoginPage());
                redirectStrategy.sendRedirect(request, response, securityProperties.getBrowser().getLoginPage());
            }
        }
        return new SimpleResponse("访问的服务需要身份认证，请引导用户到登录页");
    }
}
